<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">


                <el-button type="primary" @click="()=>this.editVisible1=true" v-if="hasPermission('user:add')">添加用户</el-button>
            </div>
            <el-table
                    :data="userList.filter(user=>user.user.isDeleted===0)"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"

            >
                <el-table-column label="ID" width="55" align="center">
                    <template slot-scope="scope">
                        {{scope.row.user.userId}}
                    </template>
                </el-table-column>
                <el-table-column label="用户名">
                    <template slot-scope="scope">
                        {{scope.row.user.username}}
                    </template>
                </el-table-column>
                <el-table-column label="角色名">
                    <template slot-scope="scope">
                        <el-tag type="info" v-for="role in scope.row.roleList">
                            {{role.description}}
                        </el-tag>
                    </template>
                </el-table-column>


                <el-table-column label="菜单&权限">
                    <template slot-scope="scope">
                        <el-row v-for="menu in scope.row.menuList">
                            <span style="margin-right: 4px">{{menu.menuName}}</span>
                            <el-tag v-for="permission in menu.permissionList"
                                    style="margin-right: 7px;margin-bottom: 7px">
                                {{permission.description}}
                            </el-tag>
                        </el-row>
                    </template>

                </el-table-column>

                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.row.user.userId)" v-if="hasPermission('user:update')"
                        >编辑
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.row.user.userId)" v-if="hasPermission('user:delete')"
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>


            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="pageNum"
                        :page-size="4"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <el-dialog title="添加用户" :visible.sync="editVisible1" width="45%" label-position="left" label-width="150px"
                   size="small">
            <el-form ref="form1" :model="form1" label-width="100px" :rules="rules">
                <el-form-item label="用户名" prop="username">
                    <el-input placeholder="用户名" v-model="form1.username" style="width: 70%;"
                              :value="form1.username"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password">
                    <el-input show-password placeholder="用户密码" v-model="form1.password"></el-input>
                </el-form-item>
                <el-form-item label="添加角色">
                    <el-select v-model="selectValue" style="margin-right: 3px">
                        <el-option v-for="role in roleList" :key="role"
                                   :label="role.description"
                                   :value="role.description">
                        </el-option>
                    </el-select>
                    <el-button @click="addRoleName" style="margin-right: 3px" type="primary">添加</el-button>
                    <el-tag v-for="(roleName,index) in roles" closable="true" style="margin-right: 3px"
                            :disable-transitions="false"
                            @close="handleClose(index)">
                        {{roleName}}
                    </el-tag>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible1 = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="编辑" :visible.sync="editVisible" width="45%" label-position="left" label-width="150px"
                   size="small">
            <el-form ref="form" :model="form" label-width="100px" :rules="rules">
                <el-form-item label="用户名" prop="username">
                    <el-input placeholder="用户名" v-model="form.username"
                              :value="form.username"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password">
                    <el-input show-password placeholder="用户密码" v-model="form.password"></el-input>
                </el-form-item>
                <el-form-item label="添加角色">
                    <el-select v-model="selectValue" style="margin-right: 3px">
                        <el-option v-for="role in roleList" :key="role"
                                   :label="role.description"
                                   :value="role.description">
                        </el-option>
                    </el-select>
                    <el-button @click="addRole" style="margin-right: 3px" type="primary">添加</el-button>
                    <el-tag v-for="(role,index) in form.roles" closable="true" style="margin-right: 3px"
                            :disable-transitions="false"
                            @close="handleClose1(index)">
                        {{role.description}}
                    </el-tag>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateUser">确 定</el-button>
            </span>
        </el-dialog>


    </div>
</template>

<script>
    import { updateRole, getOnlyAllRoles } from '../../api/role';
    import { addUser, deleteUser, getAllUserPermission, getUserInfo, updateUser } from '../../api/user';
    import { hasMenu, hasPermission, permissionListContain, getPermission } from '../../utils/authority';

    export default {
        name: 'user',
        data() {
            return {
                selectValue: '',
                permissionList: [],
                permissionList1: [],
                userList: [],
                roleList: [],
                editVisible1: false,
                pageNum: 1,
                query: {
                    address: '',
                    name: '',
                    pageIndex: 1,
                    pageSize: 10
                },
                tableData: [],
                multipleSelection: [],
                delList: [],
                editVisible: false,
                pageTotal: 0,
                selectArr: [],
                selectArr1: [],
                roleVO: {},
                roles: [],
                form1: {
                    roles: [],
                    username: '',
                    password: ''

                },
                form: {
                    roles: [],
                    userId: '',
                    password: '',
                    username: ''
                },
                idx: -1,
                id: -1,
                rules2: {
                    description: [
                        { required: true, message: '角色名不能为空', trigger: 'change' }
                    ],
                    roleName: [
                        { required: true, message: '角色码不能为空', trigger: 'change' }
                    ]
                },
                rules: {
                    username: [
                        { required: true, message: '用户名不能为空', trigger: 'change' }
                    ],
                    password: [
                        { required: true, message: '密码不能为空', trigger: 'change' }
                    ]

                }
            };
        },
        created() {

            this.getData();
        },
        methods: {
            permissionContain(permissionList) {
                return permissionListContain(permissionList);
            },
            hasPermission(permission) {
                return hasPermission(permission);
            },
            hasMenu(menuCode) {
                return hasMenu(menuCode);
            },
            addRole() {

                let tempArr = this.roleList.map(role => role.description);
                if (tempArr.indexOf(this.selectValue) === -1) {
                    this.$message.error('用户已有该角色');
                } else {
                    let index = tempArr.indexOf(this.selectValue);
                    this.form.roles.push(this.roleList[index]);
                }
            },
            handleClose1(index) {
                this.form.roles.splice(index, 1);

            },
            handleClose(index) {
                this.roles.splice(index, 1);
                console.log(JSON.stringify(this.roles));
            },
            addRoleName() {
                if (this.roles.indexOf(this.selectValue) !== -1) {
                    this.$message.error('已添加过');
                } else {
                    this.roles.push(this.selectValue);
                }
            },
            savePermission(permissionList, index) {
                if (this.selectArr[index] === 'default') {
                    this.selectArr[index] = 'success';
                    permissionList.map(item => item.description).forEach(item => this.form.permissionList.push(item));
                } else {
                    this.selectArr[index] = 'default';
                    this.form.permissionList = this.form.permissionList.filter(item => permissionList.map(item => item.description).indexOf(item) === -1);

                }

            },
            // 获取 easy-mock 的模拟数据
            getData() {
                getAllUserPermission().then(res => {
                    this.userList = res.data.data.list;
                    this.total = res.data.data.total;
                });

                getOnlyAllRoles().then(res => {
                    this.roleList = res.data.data;
                });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageIndex', 1);
                this.getData();
            },
            // 删除操作
            handleDelete(userId) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        deleteUser({
                            userId: userId
                        }).then(res => {
                            if (res.data.resultCode === 204) {
                                this.$message.success('删除成功');
                                this.getData();
                            } else {
                                this.$message.error('删除失败');
                            }
                        });

                    })
                    .catch(() => {
                    });
            },
            // 编辑操作
            handleEdit(userId) {
                console.log(userId);
                getUserInfo({
                    userId: userId
                }).then(res => {
                    let userInfo = res.data.data;
                    this.editVisible = true;
                    this.form.roles = userInfo.roles;
                    this.form.userId = userInfo.user.userId;
                    this.form.password = userInfo.user.password;
                    this.form.username = userInfo.user.username;
                    this.editVisible = true;
                });
            },


            updateRole() {
                this.$refs.form1.validate(valid => {
                    if (valid) {
                        let descriptionList = this.form1.permissionList;
                        delete this.form1['permissionList'];
                        this.form1['descriptions'] = descriptionList;
                        updateRole(JSON.stringify(this.form1)).then(res => {
                            if (res.data.resultCode === 201) {
                                this.$message.success('修改成功');
                                this.form1 = {
                                    roleName: '',
                                    permissionList: [],
                                    description: ''
                                };
                                this.editVisible1 = false;
                                this.getData();
                            } else {
                                this.$message.error('修改失败');
                                console.log('error submit!!');


                                return false;
                            }
                        });

                    }
                });
            },


            updateUser() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        this.form['user'] = {
                            userId: this.form.userId,
                            username: this.form.username,
                            password: this.form.password
                        };
                        delete this.form['password'];
                        delete this.form['username'];
                        delete this.form['userId'];
                        updateUser(JSON.stringify(this.form)).then(res => {
                            if (res.data.resultCode === 201) {
                                this.$message.success('修改成功');
                                this.form1 = {
                                    roles: [],
                                    username: '',
                                    password: '',
                                    userId: ''

                                };
                                this.editVisible = false;
                                this.getData();

                            } else {
                                this.$message.error('修改失败');
                                console.log('error submit!!');

                                return false;
                            }
                        });
                    }
                });
            },
            // 保存编辑
            saveEdit() {

                this.$refs.form1.validate(valid => {
                    if (valid) {
                        console.log(this.roles);
                        let descriptionList = this.roleList.map(item => item.description);
                        console.log(descriptionList);
                        let roles = [];

                        for (let i = 0; i < this.roles.length; i++) {
                            let role = this.roles[i];
                            let index = descriptionList.indexOf(role);
                            if (index !== -1) {
                                roles.push(this.roleList[index]);
                            }
                        }

                        this.form1.roles = roles;
                        this.form1['user'] = {
                            username: this.form1.username,
                            password: this.form1.password
                        };
                        delete this.form1['username'];
                        delete this.form1['password'];
                        addUser(JSON.stringify(this.form1)).then(res => {
                            if (res.data.resultCode === 201) {
                                this.$message.success('添加成功');
                                this.form1 = {
                                    roles: [],
                                    username: '',
                                    password: ''

                                };
                                this.editVisible1 = false;
                                this.getData();

                            } else {
                                this.$message.error('添加失败');
                                console.log('error submit!!');

                                return false;
                            }
                        });

                    }
                });


            },
            // 分页导航
            handlePageChange(val) {
                getAllRoles({
                    pageNum: val
                }).then(res => {
                    this.roleList = res.data.data.list;
                    this.pageNum = res.data.data.pageNum;
                });
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
</style>
